<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP 代理测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .container {
            background: rgba(255, 255, 255, 0.1);
            padding: 30px;
            border-radius: 15px;
            backdrop-filter: blur(10px);
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 10px;
            border-left: 4px solid #4CAF50;
        }
        .test-section.error {
            border-left-color: #f44336;
        }
        .test-section.testing {
            border-left-color: #ff9800;
        }
        button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px 5px;
        }
        button:hover {
            background: #45a049;
        }
        button:disabled {
            background: #cccccc;
            cursor: not-allowed;
        }
        .status {
            font-weight: bold;
            margin-left: 10px;
        }
        .success { color: #4CAF50; }
        .error { color: #f44336; }
        .testing { color: #ff9800; }
        pre {
            background: rgba(0, 0, 0, 0.3);
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
        }
        input[type="text"] {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: rgba(255, 255, 255, 0.9);
            color: #333;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🐘 PHP 代理测试</h1>
        <p>此页面用于测试您的 PHP 代理脚本是否正常工作。</p>
        
        <div class="test-section">
            <h3>📋 测试配置</h3>
            <label>BFL API 密钥:</label>
            <input type="text" id="apiKey" placeholder="输入您的 BFL API 密钥" value="b4a3039e-d8ed-45a5-ad6b-3c4334b28c6c">
            
            <label>测试提示词:</label>
            <input type="text" id="testPrompt" placeholder="输入测试提示词" value="a beautiful sunset over mountains">
        </div>
        
        <button onclick="testPhpProxy()">🚀 测试 PHP 代理</button>
        <button onclick="testEndpoints()">🌐 测试所有端点</button>
        <button onclick="clearResults()">🧹 清除结果</button>
        
        <div id="results"></div>
    </div>

    <script>
        const endpoints = ['global', 'us', 'eu', 'us1', 'eu1'];

        async function testPhpProxy() {
            const apiKey = document.getElementById('apiKey').value;
            const prompt = document.getElementById('testPrompt').value;
            
            if (!apiKey || !prompt) {
                alert('请填写 API 密钥和测试提示词');
                return;
            }

            const resultsDiv = document.getElementById('results');
            resultsDiv.innerHTML = '<div class="test-section testing"><h3>🔄 测试中...</h3></div>';

            try {
                // 测试生成请求
                console.log('🚀 开始测试 PHP 代理生成请求...');
                
                const generateUrl = '/api-proxy.php?action=generate&endpoint=global';
                const response = await fetch(generateUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'x-key': apiKey
                    },
                    body: JSON.stringify({
                        prompt: prompt,
                        width: 1024,
                        height: 576,
                        prompt_upsampling: true,
                        safety_tolerance: 2,
                        output_format: 'jpeg'
                    })
                });

                const result = await response.json();
                
                if (response.ok && result.id) {
                    resultsDiv.innerHTML = `
                        <div class="test-section">
                            <h3>✅ PHP 代理测试成功</h3>
                            <div class="status success">生成请求提交成功</div>
                            <div>任务ID: ${result.id}</div>
                            <div>轮询URL: ${result.polling_url}</div>
                            <pre>${JSON.stringify(result, null, 2)}</pre>
                            <button onclick="testPolling('${result.polling_url}', '${apiKey}')">🔄 测试轮询</button>
                        </div>
                    `;
                } else {
                    throw new Error(result.error || `HTTP ${response.status}`);
                }
            } catch (error) {
                resultsDiv.innerHTML = `
                    <div class="test-section error">
                        <h3>❌ PHP 代理测试失败</h3>
                        <div class="status error">错误: ${error.message}</div>
                        <div>请检查:</div>
                        <ul>
                            <li>api-proxy.php 文件是否存在</li>
                            <li>PHP 服务器是否正常运行</li>
                            <li>API 密钥是否正确</li>
                            <li>网络连接是否正常</li>
                        </ul>
                    </div>
                `;
            }
        }

        async function testPolling(pollingUrl, apiKey) {
            const resultsDiv = document.getElementById('results');
            
            try {
                const pollUrl = `/api-proxy.php?action=poll&url=${encodeURIComponent(pollingUrl)}`;
                const response = await fetch(pollUrl, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json',
                        'x-key': apiKey
                    }
                });

                const result = await response.json();
                
                if (response.ok) {
                    resultsDiv.innerHTML += `
                        <div class="test-section">
                            <h3>📊 轮询测试结果</h3>
                            <div>状态: ${result.status}</div>
                            <div>响应时间: ${new Date().toLocaleTimeString()}</div>
                            <pre>${JSON.stringify(result, null, 2)}</pre>
                        </div>
                    `;
                } else {
                    throw new Error(result.error || `HTTP ${response.status}`);
                }
            } catch (error) {
                resultsDiv.innerHTML += `
                    <div class="test-section error">
                        <h3>❌ 轮询测试失败</h3>
                        <div class="status error">错误: ${error.message}</div>
                    </div>
                `;
            }
        }

        async function testEndpoints() {
            const apiKey = document.getElementById('apiKey').value;
            
            if (!apiKey) {
                alert('请填写 API 密钥');
                return;
            }

            const resultsDiv = document.getElementById('results');
            resultsDiv.innerHTML = '';

            for (const endpoint of endpoints) {
                const div = document.createElement('div');
                div.id = `result-${endpoint}`;
                div.className = 'test-section testing';
                div.innerHTML = `
                    <h3>端点: ${endpoint}</h3>
                    <div class="status testing">🔄 测试中...</div>
                `;
                resultsDiv.appendChild(div);

                try {
                    const testUrl = `/api-proxy.php?action=generate&endpoint=${endpoint}&debug=1`;
                    const startTime = Date.now();
                    
                    const response = await fetch(testUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'x-key': apiKey
                        },
                        body: JSON.stringify({
                            prompt: 'test',
                            width: 512,
                            height: 512
                        })
                    });

                    const endTime = Date.now();
                    const responseTime = endTime - startTime;
                    const result = await response.json();

                    if (response.ok) {
                        div.className = 'test-section';
                        div.innerHTML = `
                            <h3>端点: ${endpoint}</h3>
                            <div class="status success">✅ 成功 (${responseTime}ms)</div>
                            <div>状态码: ${response.status}</div>
                            <pre>${JSON.stringify(result, null, 2).substring(0, 300)}...</pre>
                        `;
                    } else {
                        throw new Error(result.error || `HTTP ${response.status}`);
                    }
                } catch (error) {
                    div.className = 'test-section error';
                    div.innerHTML = `
                        <h3>端点: ${endpoint}</h3>
                        <div class="status error">❌ 失败</div>
                        <div>错误: ${error.message}</div>
                    `;
                }
            }
        }

        function clearResults() {
            document.getElementById('results').innerHTML = '';
        }
    </script>
</body>
</html>
